package com.flk.oauth.security;

import com.flk.oauth.entity.OauthUser;
import com.flk.oauth.repository.OauthUserRepository;
import com.flk.oauth.service.IOauthUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author xxwy
 * on 2018/10/15 0015
 * todo：手机号验证：65
 */
@Service("userDetailsService")
@Slf4j
public class DomainUserDetailsService implements UserDetailsService {

    @Autowired
    private OauthUserRepository oauthUserRepository;

    @Autowired
    private IOauthUserService iOauthUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //OauthUser byUsername = oauthUserRepository.findByUsername(username);
        OauthUser byUsername = null;
        if (isMobile(username)) {
            byUsername = oauthUserRepository.findByPhone(username);
        } else {
            byUsername = oauthUserRepository.findByUsername(username);
        }
        if (byUsername == null) {
            //throw new UsernameNotFoundException(username+"用户不存在");
            //自动注册
            OauthUser build = null;
            if (isMobile(username)) {
                build = OauthUser.builder().phone(username).password(username).build();
            } else {
                build = OauthUser.builder().username(username).password(username).build();
            }
            //写入数据库
            byUsername = iOauthUserService.insertOauthUser(build);
        }
        if (byUsername == null) {
            throw new BadCredentialsException("请重新登录");
        }
        return byUsername;
    }

    private boolean isMobile(String str) {
        Pattern p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
        Matcher m = p.matcher(str);
        boolean b = m.matches();
        //return b;
        return true;
    }


}
